package com.x.client.fragment

import android.support.v4.content.ContextCompat
import android.support.v7.widget.DividerItemDecoration
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.alibaba.android.arouter.launcher.ARouter
import com.chad.library.adapter.base.BaseQuickAdapter
import com.gg.baselibrary.BaseFragment
import com.gg.utils.GsonUtil
import com.gg.utils.StatusUtils
import com.gg.utils.Utils
import com.gg.widget.RangeBar
import com.jakewharton.rxbinding2.view.RxView
import com.lsxiao.apollo.core.annotations.Receive
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener
import com.socks.library.KLog
import com.x.client.R
import com.x.client.adapter.CarListAdapter
import com.x.client.adapter.PriceAdapter
import com.x.client.bean.Car
import com.x.client.bean.CarStateBus
import com.x.client.bean.PriceItem
import com.x.client.net.ApiFactory
import com.x.client.net.Composers
import com.x.client.utils.*
import com.zyyoona7.popup.EasyPopup
import io.reactivex.Observable
import kotlinx.android.synthetic.main.fragment_buy_car.*
import kotlinx.android.synthetic.main.list_car.*
import kotlinx.android.synthetic.main.menu_car_list_filter.*
import java.util.concurrent.TimeUnit

/**
 * Creator : GG
 * Date    : 2018/5/21
 * Mail    : gg.jin.yu@gmai.com
 * Explain :
 */
class BuyCarFragment : BaseFragment(), OnRefreshLoadMoreListener {


    private lateinit var mSortPop: EasyPopup

    private lateinit var mPricePop: EasyPopup

    private lateinit var priceRangeBar: RangeBar
    private lateinit var priceRecycler: RecyclerView
    private lateinit var price: TextView

    private var bus: CarStateBus = CarStateBus()

    private lateinit var mNoDataView: View


    private val adapter: CarListAdapter by lazy { CarListAdapter() }


    private var mPageIndex = 1

    private val mAdapter: PriceAdapter by lazy {
        PriceAdapter(data = listOf(PriceItem(name = "不限"), PriceItem(name = "0~3万"), PriceItem(name = "3~5万"), PriceItem(name = "5~10万"),
                PriceItem(name = "10~15万"), PriceItem(name = "15~20万"), PriceItem(name = "20~30万"), PriceItem(name = "30~50万"), PriceItem(name = "50万以上")))
    }


    private val priceArray: Array<String>  by lazy { resources.getStringArray(R.array.price_array) }


    companion object {
        fun newInstance() = BuyCarFragment()
    }

    override fun getLayoutResId(): Int = R.layout.fragment_buy_car


    override fun initView() {
        super.initView()

        statusBar.layoutParams.apply {
            height = StatusUtils.getStatusBarHeight(context!!)
        }

        initList()

        initPopWindows()

        RxView.clicks(sortText)
                .throttleFirst(1, TimeUnit.SECONDS)
                .compose(this.bindToLifecycle())
                .subscribe {
                    if (this::mSortPop.isInitialized) {
                        mSortPop.showAsDropDown(sortText)
                    }
                }

        RxView.clicks(priceText)
                .throttleFirst(1, TimeUnit.SECONDS)
                .compose(this.bindToLifecycle())
                .subscribe {
                    if (this::mPricePop.isInitialized) {
                        definePrice.visibility = View.VISIBLE
                        mPricePop.showAsDropDown(priceText)
                    }
                }
        RxView.clicks(definePrice)
                .throttleFirst(1, TimeUnit.SECONDS)
                .compose(this.bindToLifecycle())
                .subscribe {
                    if (this::mPricePop.isInitialized) {
                        swipeRefresh.autoRefresh()
                        mPricePop.dismiss()
                    }
                }

        RxView.clicks(brandText)
                .throttleFirst(1, TimeUnit.SECONDS)
                .compose(this.bindToLifecycle())
                .subscribe {
                    ARouter.getInstance()
                            .build(RouterClass.brand)
                            .withParcelable(RouterField.data, bus)
                            .navigation()
                }

        RxView.clicks(filterText)
                .throttleFirst(1, TimeUnit.SECONDS)
                .compose(this.bindToLifecycle())
                .subscribe {
                    ARouter.getInstance()
                            .build(RouterClass.filter)
                            .withParcelable(RouterField.data, bus)
                            .navigation()
                }

        swipeRefresh.autoRefresh()

    }

    private fun initList() {
        swipeRefresh.setOnRefreshLoadMoreListener(this)
        swipeRefresh.setDisableContentWhenRefresh(false)
        swipeRefresh.setDisableContentWhenLoading(false)
        swipeRefresh.setEnableOverScrollDrag(true)
        swipeRefresh.setEnableLoadMoreWhenContentNotFull(true)
        swipeRefresh.setEnableOverScrollBounce(true)

        recyclerView.layoutManager = LinearLayoutManager(context)
        recyclerView.addItemDecoration(DividerItemDecoration(context, DividerItemDecoration.VERTICAL).apply {
            setDrawable(ContextCompat.getDrawable(this@BuyCarFragment.context!!, R.drawable.divider_ll_grey_h)!!)
        })

        mNoDataView = layoutInflater.inflate(R.layout.empty_view, recyclerView as ViewGroup, false)

        mNoDataView.setOnClickListener {
            onRefresh(swipeRefresh)
        }

        recyclerView.adapter = adapter

        adapter.onItemClickListener = BaseQuickAdapter.OnItemClickListener { _, _, position ->
            if (Utils.isFastClick()) {
//                ARouter.getInstance().build(RouterClass.carSaleDetail).withString(RouterFieldTag.carId, car.carId).navigation()
            }
        }
    }


    private fun initPopWindows() {
        if (!this::mSortPop.isInitialized) {
            mSortPop = EasyPopup.create()
                    .setContext(activity)
                    .setContentView(R.layout.pop_sort, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
                    .setAnimationStyle(R.style.TopPopAnim)
                    //是否允许点击PopupWindow之外的地方消失
                    .setFocusAndOutsideEnable(true)
                    //允许背景变暗
                    .setBackgroundDimEnable(true)
                    //变暗的透明度(0-1)，0为完全透明
                    .setDimValue(0.4f)
                    .setDimView(recyclerView)
                    .apply()

            initSortView()
        }
        if (!this::mPricePop.isInitialized) {
            mPricePop = EasyPopup.create()
                    .setContext(activity)
                    .setContentView(R.layout.pop_price, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
                    .setAnimationStyle(R.style.TopPopAnim)
                    //是否允许点击PopupWindow之外的地方消失
                    .setFocusAndOutsideEnable(false)
                    //允许背景变暗
                    .setBackgroundDimEnable(true)
                    //变暗的透明度(0-1)，0为完全透明
                    .setDimValue(0.4f)
                    .setDimView(recyclerView)
                    .setOnDismissListener {
                        definePrice.visibility = View.INVISIBLE
                    }
                    .apply()
            mPricePop.popupWindow.isFocusable = false
            priceRangeBar = mPricePop.contentView.findViewById(R.id.price_rangeBar)
            priceRecycler = mPricePop.contentView.findViewById(R.id.price_choose)
            price = mPricePop.contentView.findViewById(R.id.price)
            initPriceView()
        }
    }

    private fun initPriceView() {

        if (bus.pricePosition != -1) {
            mAdapter.data[bus.pricePosition ?: 0].status = true
        } else {
            if (bus.fromRetailPriceIndex != null && bus.toRetailPriceIndex != null) {
                priceRangeBar.setRange(bus.fromRetailPriceIndex ?: 0, bus.toRetailPriceIndex
                        ?: 8)
                setPrice(bus.fromRetailPriceIndex ?: 0, bus.toRetailPriceIndex ?: 8)
            }
        }

        priceRangeBar.setOnRangeSelectedListener { left, right ->
            setPrice(left, right)
        }

        priceRecycler.layoutManager = GridLayoutManager(activity, 3)
        priceRecycler.adapter = mAdapter



        mAdapter.onItemClickListener = BaseQuickAdapter.OnItemClickListener { _, _, position ->
            if (bus.pricePosition != -1) {
                mAdapter.data[bus.pricePosition ?: 0].status = false
                mAdapter.notifyItemChanged(bus.pricePosition ?: 0)
            }
            when (position) {
                0 -> {
                    bus.fromRetailPrice = null
                    bus.toRetailPrice = null
                }
                1 -> {
                    bus.fromRetailPrice = 0.0
                    bus.toRetailPrice = 3.0
                }
                2 -> {
                    bus.fromRetailPrice = 3.0
                    bus.toRetailPrice = 5.0
                }
                3 -> {
                    bus.fromRetailPrice = 5.0
                    bus.toRetailPrice = 10.0
                }
                4 -> {
                    bus.fromRetailPrice = 10.0
                    bus.toRetailPrice = 15.0
                }
                5 -> {
                    bus.fromRetailPrice = 15.0
                    bus.toRetailPrice = 20.0
                }
                6 -> {
                    bus.fromRetailPrice = 20.0
                    bus.toRetailPrice = 30.0
                }
                7 -> {
                    bus.fromRetailPrice = 30.0
                    bus.toRetailPrice = 50.0
                }
                8 -> {
                    bus.fromRetailPrice = 50.0
                    bus.toRetailPrice = null
                }
            }
            bus.pricePosition = position
            if (bus.pricePosition != -1) {
                mAdapter.data[bus.pricePosition ?: 0].status = true
                mAdapter.notifyItemChanged(bus.pricePosition ?: 0)
            }
            priceRangeBar.setRange(0, 8)
            if (mPricePop.isShowing) {
                mPricePop.dismiss()
                swipeRefresh.autoRefresh()
            }
        }
    }


    private fun setPrice(left: Int, right: Int) {
        bus.fromRetailPriceIndex = left
        bus.toRetailPriceIndex = right
        if (right == priceArray.size - 1 && left == 0) {
            price.text = priceArray[right]
            bus.fromRetailPrice = null
            bus.toRetailPrice = null
        } else if (right == priceArray.size - 1 && left != 0) {
            price.text = priceArray[left] + "万以上"
            bus.fromRetailPrice = priceArray[left].toDouble()
            bus.toRetailPrice = null
        } else if (right != priceArray.size - 1 && left != 0) {
            price.text = priceArray[left] + "~" + priceArray[right] + "万"
            bus.fromRetailPrice = priceArray[left].toDouble()
            bus.toRetailPrice = priceArray[right].toDouble()
        } else if (right != priceArray.size - 1 && left == 0) {
            price.text = priceArray[right] + "万以内"
            bus.fromRetailPrice = null
            bus.toRetailPrice = priceArray[right].toDouble()
        }
        if (left == 0 && right == 8) {
            bus.pricePosition = 0
            mAdapter.data[bus.pricePosition ?: 0].status = true
            mAdapter.notifyItemChanged(bus.pricePosition ?: 0)
        } else {
            if (bus.pricePosition != -1) {
                mAdapter.data[bus.pricePosition ?: 0].status = false
                mAdapter.notifyItemChanged(bus.pricePosition ?: 0)
                bus.pricePosition = -1
            }
        }
    }

    private fun initSortView() {
        setSortClick(CarStateBus.UpdateNewest, mSortPop.contentView.findViewById(R.id.newCreate))
        setSortClick(CarStateBus.PriceLowest, mSortPop.contentView.findViewById(R.id.lowPrice))
        setSortClick(CarStateBus.PriceHighest, mSortPop.contentView.findViewById(R.id.highPrice))
        setSortClick(CarStateBus.LicenseDateShortest, mSortPop.contentView.findViewById(R.id.lowAge))
        setSortClick(CarStateBus.MileageShortest, mSortPop.contentView.findViewById(R.id.lowMileage))
    }

    private fun setSortClick(sortStr: String, view: View) {

        UIHelper.setItem(view = view, title = sortStr, isCheck = bus.sortType == sortStr,
                rightImg = R.drawable.ic_check_orange, action = View.OnClickListener {
            if (mSortPop.isShowing) {
                mSortPop.dismiss()
            }
            bus.sortType = sortStr
            sortText.text = sortStr
            initSortView()
            swipeRefresh.autoRefresh()
        })


    }

    override fun onRefresh(refreshLayout: RefreshLayout) {

        mPageIndex = 1
        getData().subscribe({
            if (it.isEmpty())
                adapter.emptyView = mNoDataView
            adapter.setNewData(it)
            swipeRefresh.finishRefresh(true)
        }, { swipeRefresh.finishRefresh(false) })

    }

    override fun onLoadMore(refreshLayout: RefreshLayout) {
        if (adapter.data.size < AppConstant.PageSize) {//数据少于15个 可以加载更多
            swipeRefresh.autoLoadMore()
        } else {
            mPageIndex += 1
            getData().subscribe({
                if (it.isEmpty()) {
                    swipeRefresh.finishLoadMoreWithNoMoreData()
                } else {
                    adapter.addData(it)
                    swipeRefresh.finishLoadMore(true)
                }
            }, {
                swipeRefresh.finishLoadMore(false)
            })
        }
    }


    private fun getData(): Observable<List<Car>> {
        return ApiFactory.getErpApi()
                .carList(
                        pageIndex = mPageIndex,
                        carOutColor = bus.carOutColor,
                        modelId = bus.modelId,
                        seriesId = bus.seriesId,
                        brandId = bus.brandId,
                        carBargainPriceState = bus.carBargainPriceState,
                        carAuthState = bus.carAuthState,
                        carDetectState = bus.carDetectState,
                        carSaleState = Car.CarSaleState_Already_Shelve,
                        carOrderState = bus.carOrderState,
                        fromRetailPrice = bus.fromRetailPrice,
                        toRetailPrice = bus.toRetailPrice,
                        fromCarAge = bus.fromCarAge,
                        toCarAge = bus.toCarAge,
                        carTypeId = bus.carTypeId,
                        fromCreateTime = bus.fromCreateTime,
                        toCreateTime = bus.toCreateTime,
                        fromMileage = bus.fromMileage,
                        toMileage = bus.toMileage,
                        orderColunm = bus.orderColunm,
                        orderMode = bus.orderMode,
                        carEnviron = bus.environ
                )
                .compose(Composers.handleError())
                .compose(this.bindToLifecycle())
    }

    override fun useBus(): Boolean = true

    @Receive(BusTag.carState)
    fun getBrand(carStateBus: CarStateBus) {
        KLog.w("car state", GsonUtil.toJson(carStateBus))
        bus.brandId = carStateBus.brandId
        bus.seriesId = carStateBus.seriesId
        KLog.w("bus", GsonUtil.toJson(bus))
        swipeRefresh.autoRefresh()
    }

    @Receive(BusTag.filter)
    fun getFilter(carStateBus: CarStateBus) {
        bus = carStateBus.copy()
        KLog.w("bus", GsonUtil.toJson(bus))

        swipeRefresh.autoRefresh()
    }


}